package com.itheima.edu.info.manager.D_Dao;

import com.itheima.edu.info.manager.E_domain.Student;

import java.util.ArrayList;

//仓管类：进行增删查改;
public class ArrayStudentDao implements BaseStudentDao {

    //创建容器：
        static Student[] students = new Student[3];
    static {
        Student student1 = new Student("223", "新民", 23, "3456");
        Student student2 = new Student("43", "gg", 33, "5555");
        Student student3 = new Student("54", "ee", 44, "34666656");

        students[0]= student1;
        students[1]= student2;
        students[2]= student3;

    }

    //添加方法：
    public boolean addStudent(Student student) {

        //将学生对象添加给容器
        //先遍历容器查看是否满了：
        for (int i = 0; i < students.length; i++) {
            //如果为空，就添加
            if (students[i]==null){
                students[i] = student;
                return true;
            }
        }
        return false;

    }

    public ArrayList<Student> findAllStudent() {
        //因为返回的是集合类型：
        //创建集合存储遍历数组的元素：
        ArrayList<Student> studentArrayList = new ArrayList<>();
        for (int i = 0; i < students.length; i++) {
            studentArrayList.add(students[i]);
        }
        return studentArrayList;
    }

    public void updateStudent(Student student,int index) {
        //根据删除的索引，找到要修改的元素：
        students[index] = student;
    }

    public void deleteStudent(int index) {//
        //获取索引：
        //已知要删除的索引,从要删除的位置开始用下一个元素进行覆盖
        //遍历数组：


        for (; index < students.length-1; index++) {
            students[index] = students[index+1];
        }
        students[index] = null;
    }

    //定义根据id获取索引的方法：
    public int getIndex(String id){
        int index = -1;
        for (int i = 0; i < students.length; i++) {
            if (id.equals(students[i].getId())){
                index = i;
            }
        }
        return index;
    }
}
